package com.learning.optimize.jdk.clazz;

import java.util.Random;

/**
 * ClassName: ClassInitialization
 * Description: Class 方法的类初始化
 * Date: 2018/7/17 22:38 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class ClassInitialization {
    public static Random rand = new Random(47);

    /**
     * Class字面量与 static final修饰的编译期静态常量 不会触发类初始化（出于加载阶段）
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        // 字面常量获取方式获取 Class 对象，不触发类初始化
        Class initable = Initable.class;
        System.out.println("After creating Initable ref");
        // 不触发类初始化
        System.out.println(Initable.staticFinal);

        // 会触发类初始化
        System.out.println(Initable.staticFinal2);
        // 会触发类初始化
        System.out.println(Initable2.staticNonFinal);
        // forName方法获取 Class 对象
        Class initable3 = Class.forName("com.learning.optimize.jdk.clazz.Initable3");
        System.out.println("After creating Initable3 ref");

        System.out.println(Initable3.staticNonFinal);

        /*
         After creating Initable ref
        47
        Initializing Initable
        258
        Initializing Initable2
        147
        Initializing Initable3
        After creating Initable3 ref
        74
        */
    }
}

class Initable {
    /**
     * 编译期静态常量
     */
    static final int staticFinal = 47;
    /**
     * 非编期静态常量
     */
    static final int staticFinal2 = ClassInitialization.rand.nextInt(1000);

    static {
        System.out.println("Initializing Initable");
    }
}

class Initable2 {
    /**
     * 静态成员变量
     */
    static int staticNonFinal = 147;

    static {
        System.out.println("Initializing Initable2");
    }
}

class Initable3 {
    /**
     * 静态成员变量
     */
    static int staticNonFinal = 74;

    static {
        System.out.println("Initializing Initable3");
    }
}

/*
*   After creating Initable ref
    47
    Initializing Initable
    258
    Initializing Initable2
    147
    Initializing Initable3
    After creating Initable3 ref
    74
* */